#!/usr/bin/env python

import sys
from lib.format_time import *
from shop_conn import *
from lib.HandleMysql import *
from lib.switch_code import *
import re
import os

sys.setdefaultencoding('utf-8')


def select_current_product(date):
    """

    :param date:
    """
    conn = set_product_conn()
    shop_id = 0
    query = "select distinct shopid from t_product where left(adddate,10)='%s' or left(postdate,10)='%s'" % (date, date)
    print "select_current_product %s" % query
    items = conn.get_results(query)
    if len(items) > 0:
        print "today we'll update %s shops" %len(items)
    for item in items:
        shop_id = item[0]
        if shop_id != 0:
            get_product_info(shop_id)


def get_product_info(shop_id):
    """

    :param shop_id:
    """
    prod_conn = set_product_conn()
    stat_conn = set_stats_conn()
    prod_count = 0
    prod_online_count = 0
    prod_sale_count = 0
    query = "select count(1) as prod_count,count(case when state=1 then 1 end),count(case when salestate=1 then 1 end) from t_product where shopid = %s" % shop_id
    print "get_product_info %s" % query
    item = prod_conn.get_results(query)
    if len(item) > 0:
        prod_count = item[0][0]
        prod_online_count = item[0][1]
        prod_sale_count = item[0][2]
    if prod_count != 0:
        print "shop:%s have %s products" %(shop_id,prod_count)
        sql = "update shop_info set prod_count = %s , prod_online_count = %s , prod_sale_count = %s where shop_id = %s;" % (
            prod_count, prod_online_count, prod_sale_count,shop_id)
        stat_conn.execute_sql(sql)
        print 'update success.'
    else:
        print 'product count equal 0 '


if __name__ == '__main__':
    date = ""
    if len(sys.argv) == 2:
        date = format_date(sys.argv[1])
        select_current_product(date)
    elif len(sys.argv) > 2:
        print len(sys.argv)
        print sys.argv[1]
        start_date = format_date(sys.argv[1])
        print "start_date = %s" %start_date
        end_date = format_date(sys.argv[2])
        print "end_date = %s" %end_date
        stat_date = start_date
        while stat_date>=start_date and stat_date<=end_date:
            print "The program of the date of %s is beginning at %s " %(stat_date,get_now())
            select_current_product(date)
            stat_date=var_date(stat_date)
            print "stat_date = %s" %stat_date
            print "The program of the date of %s is end at %s " %(stat_date,get_now())
    else:
        date = get_yesterday()
        select_current_product(date)



